package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.BlogDao;
import dao.UserDao;
import model.Blog;
import model.User;
import utils.StringUtil;
import utils.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/04/10  17:45
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        //从session中获取用户信息
        //穿false，没有session 就证明之前没有登录过，返回一个状态码403，不创建新的session
//        HttpSession session = req.getSession(false);
//        if(session == null){
//            resp.setStatus(403);
//            return;
//        }
//        //从session获取用户信息
//        User user = (User) session.getAttribute("userInfo");
        User user = UserUtil.checkUserLoginStatus(req);
        if(user == null){
            resp.setStatus(403);
            return;
        }

        //获取参数
        String blogId = req.getParameter("blogId");
        String json = null;
        //检验参数是否为空
        if(StringUtil.isEmpty(blogId)){
            //如果为空，就直接返回当前信息
            json = objectMapper.writeValueAsString(user);

        }else {
            //不为空，根据博客Id构造出用户信息
            //查询博客信息
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectById(Long.valueOf(blogId));
            //非空校验
            if(blog == null){
                resp.getWriter().write("没有此博客");
            }
            //获取用户Id
            Long userId = blog.getUserId();
            //通过userId查询用户信息
            UserDao userDao = new UserDao();
            User author = userDao.selectById(userId);
            //比较当前登录的用户ID与数据库中查出来的用户ID
            //如果用户Id相等，则当前登录用户就是作者
           int isAuthor =  user.getId() == author.getId() ? 1 : 0;
           author.setIsAuthor(isAuthor);
            //非空校验
            if(author == null){
                resp.getWriter().write("没有此用户");
            }
            //序列化成JSON字符串
           json = objectMapper.writeValueAsString(author);

        }
        resp.setStatus(200);
        resp.getWriter().write(json);
    }
}
